package cn.eoeit.alone.phoneImport.db;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import cn.eoeit.alone.phoneImport.R;
import cn.eoeit.alone.phoneImport.util.Constants;
import cn.eoeit.alone.phoneImport.util.LogUtil;


import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.text.TextUtils;


/**
 * db helper
 */
public class CacheDbOpenHelper extends SQLiteOpenHelper {
    private static final String TAG = LogUtil.getTag(CacheDbOpenHelper.class);
    private final Context mContext;
    
     CacheDbOpenHelper(Context context){ 
        super(context, Constants.CACHE_DB_NAME, null, Constants.CACHE_DB_VERSION);
        mContext = context;
    }
    
    
    @Override
    public void onCreate(SQLiteDatabase db) {
    	LogUtil.i(TAG, "-- Database onCreate --"); 
    	String sql="CREATE TABLE `city_bean` (`cid` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,`area` INTEGER DEFAULT NULL,`first_spell` TEXT(255) DEFAULT NULL,`name` TEXT(255) DEFAULT NULL,`phone_header` TEXT(255) DEFAULT NULL,`post_no` TEXT(255) DEFAULT NULL,`provance_id` INTEGER DEFAULT NULL,`provance_name` TEXT(255) DEFAULT NULL)";
        db.execSQL(sql);
        insertData(db, R.raw.citynfo);
    }
   
  
  
    

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        LogUtil.i(TAG, "-- Database onUpgrade --");

    }
		
    public BufferedReader reader(InputStream is)
  	{
      	BufferedReader reader = null;
  		try {
       		reader = new BufferedReader(new InputStreamReader(is));
  			//reader = new BufferedReader(new InputStreamReader(new CipherInputStream(is, cipherDecrypt)));
  		} catch (Exception e) {
  			reader = null;
  			e.printStackTrace();
  		} 
  		return reader;
  	}
      
      private void insertData(SQLiteDatabase db,int file)
      {
      	InputStream input = mContext.getResources().openRawResource(file);
      	BufferedReader reader = null;
      	int count = 0;
  		try {
  			reader = reader(input);
  			String line = null;
  			if(reader!=null)
  			{
  				while((line=reader.readLine())!=null)
  				{
  					if(!TextUtils.isEmpty(line)&&line.startsWith("INSERT INTO"))
  			        {						
  						db.execSQL(line);
  						LogUtil.i("insertData...", line);
  						++count;
  			        }
  				}
  			}
  			
  		} catch (SQLException e) {
  			e.printStackTrace();
  		} catch (IOException e) {
  			e.printStackTrace();
  		}finally{
  			try {
  				reader.close();
  				input.close();
  			} catch (IOException e) {
  				e.printStackTrace();
  			}
  		}
  		LogUtil.i(TAG, "执行了"+count+"条sql语句");
      }
 
    
}
